#!/bin/bash

# Copyright (c) 2023 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

ROOT_DIR=$(pwd)

NODE_HOME=$ROOT_DIR/node-v16.15.0-linux-x64
NODE_URL=https://nodejs.org/download/release/v16.15.0/node-v16.15.0-linux-x64.tar.gz
SDK_API12_URL=https://repo.huaweicloud.com/openharmony/os/5.0.0-Release/ohos-sdk-windows_linux-public.tar.gz
SDK_API12_SHASUM="7e828b95f6b0d2abf18d19757e5873b1bfd4265052798114ebec359cadcbb6a522fb1b0acda091bf0d60db92d311b64ca9400f161d89a2ee3648586ffee65c1b"

SHASUM_FILE=SHA512SUM
API_VERSION=
SDK_API9_DIR=$ROOT_DIR/ohos-sdk-9
SDK9_PKG_NAME=ohos-sdk-9.tar.gz
SDK_API10_DIR=$ROOT_DIR/ohos-sdk-10
SDK10_PKG_NAME=ohos-sdk-10.tar.gz
SDK_API11_DIR=$ROOT_DIR/ohos-sdk-11
SDK11_PKG_NAME=ohos-sdk-11.tar.gz
SDK_API12_DIR=$ROOT_DIR/ohos-sdk-12
SDK12_PKG_NAME=ohos-sdk-12.tar.gz

SDK_DIR=
SDK_URL=
SDK_PKG_NAME=
SDK_SHASUM=

OHOS_SDK_HOME=
COMPONT_NAME=

echo "ROOT_DIR=$ROOT_DIR"

verArray=(12)
sdkDirArray=($SDK_API12_DIR)
sdkUrlArray=($SDK_API12_URL)
sdkPkgName=($SDK12_PKG_NAME)
sdkSumArray=($SDK_API12_SHASUM)
sdkNum=${#sdkDirArray[@]}

function prepare_nodejs() {
    echo "prepare nodejs ############"
    if [ ! -d "$NODE_HOME" ]
    then
        wget --no-check-certificate $NODE_URL
        if [ $? -ne 0 ]
        then
            echo "download nodejs failed!"
            return 1
        fi
        local node_name=${NODE_URL##*/}
        tar -zxf $node_name
        chmod 777 $NODE_HOME/bin/*
    fi
    export PATH=$NODE_HOME:$PATH
    export NODE_HOME=${NODE_HOME}
    export PATH=$NODE_HOME/bin:$PATH
    $NODE_HOME/bin/npm config set @ohos:registry=https://repo.harmonyos.com/npm/
    $NODE_HOME/bin/npm config set lockfile=false
}

function get_samples_modules() {
    local olddir=`pwd`
    local name=$1
    local retval=0
    local modulesflag=false
    local paths=()
    local urls=()
    local branchs=()
    cd $ROOT_DIR/openharmony_tpc_samples

    while read line
    do 
        local tmp=`echo $line | grep submodule`
        if [ ! -z "$tmp" ]
        then
            tmp=`echo $line | grep $name`
            if [ ! -z "$tmp" ]
            then
                modulesflag=true
                continue
            fi
        fi
        if [ $modulesflag == true ]
        then
            tmp=`echo $line | grep "path"`
            if [ ! -z "$tmp" ]
            then
                local path=${line##*"= "}
                path=${path%/*}
                paths[${#paths[@]}]=${path}
                continue
            fi
            tmp=`echo $line | grep "url"`
            if [ ! -z "$tmp" ]
            then
                local url=${line##*"= "}
                urls[${#urls[@]}]=${url}
                continue
            fi
            tmp=`echo $line | grep "branch"`
            if [ ! -z "$tmp" ]
            then
                local branch=${line##*"= "}
                branchs[${#branchs[@]}]=${branch}
            else
                branchs[${#branchs[@]}]=""
            fi
        fi
    done < .gitmodules

    if [ $modulesflag == true ]
    then
        git config http.sslverify false     # 关闭SSL校验
        for (( i=0; i<${#paths[*]};i++ ))
        do
            local path=${paths[$i]}
            local url=${urls[$i]}
            local branch=${branchs[$i]}
            cd $path
            if [[ -z $"branch" ]] || [[ "$branch" == "" ]]
            then
                git lfs clone $url --recursive
            else
                git lfs clone $url -b $branch --recursive
            fi
            cd $OLDPWD
        done
    fi

    cd $olddir
    return $retval
}

function get_openharmony_tpc_samples() {

    local diff_url=$1.diff
    local diff_name=${diff_url##*/}
    local retval=1
    local compont_name=
    if [ ! -f $diff_name ]
    then
        wget --no-check-certificate $diff_url
        if [ $? -ne 0 ]
        then
            echo "download $diff_name failed!"
            reutrn $retval
        fi
    fi

    local diff_str=`cat $diff_name | grep "diff --git"`

    for diff in $diff_str
    do
        local tmp=`echo $diff | grep "/"`
        if [ ! -z "$tmp" ]
        then
            tmp=${tmp#*/}
            local tmp_name=${tmp%%/*}
            if [ -d $COMPONT_NAME/$tmp_name ]
            then
                if [ -z $compont_name ]
                then
                    compont_name=$tmp_name
                    retval=0
                else
                    if [ "$compont_name" != "$tmp_name" ]   #  判断是否一次PR提交多个demo的修改
                    then
                        echo "One submission only supports modification of one third-party library!"
                        retval=1
                        break
                    fi
                fi
            else
                if [ -z $compont_name ] ## 未记录到有修改/新增的目录，当前目录又不存在，判断为删除当前目录
                then
                    retval=255
                fi
            fi
        fi
    done

    if [ $retval -eq 0 ]
    then
        if [ -e $COMPONT_NAME/.gitmodules ]
        then
            get_samples_modules $compont_name
        fi
        COMPONT_NAME=$COMPONT_NAME/$compont_name
    fi

    echo "COMPONT_NAME:$COMPONT_NAME"

    return $retval
}

function init_sdk_whith_apiversion() {
    if [ ! -f "build-profile.json5" ]
    then
        cd ./h5_sample/h5_sample
        echo "当前目录没有build-profile.json5文件，已切换到 h5_sample/h5_sample 目录"
    else
        echo "当前目录存在build-profile.json5文件，不需要切换目录"
    fi
    local tmpVersion=12
    echo "$tmpVersion"
    local ret=1
    for((i=0; i<${sdkNum}; i++))
    do
        local tmpVer=`echo "${tmpVersion}" | grep "${verArray[$i]}"`
        if [ ! -z "${tmpVer}" ]
        then
            echo "API${verArray[$i]}"
            API_VERSION=${verArray[$i]}
            SDK_DIR=${sdkDirArray[$i]}
            SDK_URL=${sdkUrlArray[$i]}
            SDK_PKG_NAME=${sdkPkgName[$i]}
            SDK_SHASUM=${sdkSumArray[$i]}
            ret=0
            break
        fi
    done
    if [ $ret -eq 0 ]
    then
        export OHOS_SDK_HOME=$SDK_DIR/linux
    else
        echo "get SDK version failed!"
    fi

    return $ret
}

function get_aki_apiversion() {
    local res = 0
    cd aki/platform/ohos/publish
    init_sdk_whith_apiversion
    res=$?
    cd $OLDPWD

    export COMPONT_NAME=$COMPONT_NAME

    return $res
}

function get_apiversion(){
    local res=0
    local pr_name=$1
    if [[ $pr_name == *openharmony-tpc* ]]
    then
        pr_name=${pr_name#*openharmony-tpc/}
    else
        pr_name=${pr_name#*openharmony-sig/}
    fi
    

    if [[ $pr_name == *merge_requests* ]]
    then
        pr_name=${pr_name%/merge_requests*}
    fi
    
    COMPONT_NAME=${pr_name%/pulls*}
    COMPONT_NAME=${pr_name%/merge_requests*}
    echo "COMPONT_NAME=$COMPONT_NAME"
    if [ "x$COMPONT_NAME" == "xmanifest" ]
    then
        echo "*************manifest***************";
        return 0;
    fi

    if [ "x$COMPONT_NAME" == "xaki" ]
    then
        get_aki_apiversion
        return $?
    fi

    if [ "x$COMPONT_NAME" == "xopenharmony_tpc_samples" ]
    then
        get_openharmony_tpc_samples $1
        res=$?
        if [ $res -eq 255 ]
        then
            echo "delete samples!"
            return 0
        elif [ $res -ne  0 ]
        then
            echo "get_openharmony_tpc_samples failed!!!"
            return 1
        fi
    fi

    cd $COMPONT_NAME
    init_sdk_whith_apiversion
    res=$?
    cd $OLDPWD

    export COMPONT_NAME=$COMPONT_NAME

    return $res
}

function prepare_ohpm() {
    if [ ! -d ohpm ]
    then
        git clone https://gitee.com/zhong-luping/ohpm_tools.git
        if [ $? -ne 0 ]
        then
            echo "failed to download ohpm tools!!!"
            return 1
        fi
        cp ohpm_tools/ohpm.tar ./
        tar -xf ohpm.tar
        rm -rf ohpm.tar ohpm_tools
    fi
    return 0
}

function prepare_sdk(){
    old_dir=`pwd`
    echo "prepare sdk ###############################"
    echo "$old_dir"

    if [ $API_VERSION -lt 11 ]
    then
        cd $SDK_DIR/linux/$API_VERSION/ets/build-tools/ets-loader
        $NODE_HOME/bin/npm install
        if [ $? -ne 0 ]
        then
            echo "ets-loader npm install failed!"
            cd $old_dir
            return 1
        fi
    
        cd $SDK_DIR/linux/$API_VERSION/js/build-tools/ace-loader
        $NODE_HOME/bin/npm install
        if [ $? -ne 0 ]
        then
            echo "ace-loader npm install failed!"
            cd $old_dir
            return 1
        fi
    fi
    cd $old_dir

    return 0
}

function check_sdk_sum() {

    local sdkdir=$1
    local sdksum=$2
    echo "sdkdir=$sdkdir"
    if [ -d $sdkdir ]
    then
        if [ -f "$sdkdir/$SHASUM_FILE" ]
        then
            local shasum=`cat $sdkdir/$SHASUM_FILE`
            shasum=${shasum:0:128}

            if [ "x$shasum" == "x$sdksum" ]
            then
                echo "no need change the sdk!!"
                return 0
            fi
            echo "$shasum != $sdksum"
            echo "need change sdk!!"
        fi
        rm -rf $sdkdir*
        echo "rm -rf $sdkdir"
    fi

    return 0
}

function check_pkg_sum() {
    local pkgname=$1
    local sdksum=$2

    if [ -f $pkgname ]
    then
        local shasum=`sha512sum $pkgname`
        shasum=${shasum:0:128}
        if [ "x$shasum" == "x$sdksum" ]
        then
            echo "the pkg $pkgname is correct!"
            return 0
        fi
        echo "the pkg $pkgname is uncorrect, should be deleted!!"
        rm -f $pkgname
    fi

    return 0
}

function predowload_sdk() {
    old_dir=`pwd`
    echo "predowload sdk ###############################"
    echo "$old_dir"

    for (( i=0;i<$sdkNum;i++))
    do
        local apiver=${verArray[$i]}
        local sdkdir=${sdkDirArray[$i]}
        local sdksum=${sdkSumArray[$i]}
        local sdkurl=${sdkUrlArray[$i]}
        local pkgname=${sdkPkgName[$i]}

        check_sdk_sum $sdkdir $sdksum
        if [ ! -d "$sdkdir" ]
        then
            echo "$pkgname"
            check_pkg_sum $pkgname $sdksum
            if [ ! -f $pkgname ]
            then
                echo "start download api$apiver sdk"
                curl -L $sdkurl --output $pkgname
                if [ $? -ne 0 ]
                then    
                    echo "download sdk api $apiver failed! sdk url:$sdkurl"
                    rm -f $pkgname
                    return 1
                fi
            fi

            mkdir $sdkdir
            tar -zxf $pkgname -C $sdkdir
            if [ -d $sdkdir/ohos-sdk ]
            then
                mv $sdkdir/ohos-sdk/* $sdkdir/
                rm -rf $sdkdir/ohos-sdk
            fi

            sha512sum $pkgname > $sdkdir/$SHASUM_FILE
            cd $sdkdir/linux
            if [ $? -ne 0 ]
            then
                echo "prepare SDK $apiver failed!"
                return 1
            fi
            mkdir $apiver
            for file in $(ls ./)
            do
                if [ "$file" != "$apiver" ]
                then
                    mv $file $apiver/
                    cd $apiver/
                    unzip $file >> /dev/null
                    cd $OLDPWD
                fi
                echo "$file"
            done
        fi
        cd $old_dir
    done

    return 0
}
